// const BASE_URL = 'https://www.uinav.com'
const BASE_URL = 'https://api-ugo-dev.itheima.net'

function request({
	url,
	method = 'GET',
	isAuth = false,
	data,
	showLoading = true
}) {
	return new Promise((resolve, reject) => {
		let header = {}

		if (isAuth) {
			let token = wx.getStorageSync('token')
			// 没有token
			if (!token) {
				wx.showToast({
					title: '请先登录',
					icon: 'none',
					mask: true,
					success() {
						wx.navigateTo({
							url: '/pages/login/login.vue'
						})
						return reject(new Error('未登录'))
					}
				})
			}
		}

		// 请求前开启Loading
		if (showLoading) {
			uni.showLoading({
				title: '加载中...',
				// icon: 'loading',
				mask: true //loading中,底下不允许点击
			})
		}

		uni.request({
			url: BASE_URL + url,
			data,
			header,
			success: res => {
				// console.log(res)
				let {
					meta,
					message
				} = res.data;
				if (meta.status === 200) {
					// 成功的数据 
					resolve(message)
				} else {
					uni.showToast({
						title: meta.message,
						icon: 'none'
					})
					reject(new Error(meta.message))
				}
			},
			fail() {
				uni.showToast({
					title: '网络超时',
					icon: 'none'
				})
				reject(new Error('网络超时'))
			},
			complete() {
				// 请求结束后,关闭loading
				if (showLoading) {
					uni.hideLoading()
				}
			}
		})
	})
}

export default request
